# 项目初始化文件
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_wtf import CSRFProtect

db = SQLAlchemy()
migrate = Migrate()
# 配置csrf_token防护
csrf = CSRFProtect()

def createApp(config):
    # 实例化app
    app = Flask(__name__)
    app.config.from_object(config)
    from FlaskPro.OA.views import oa
    app.register_blueprint(oa)
    db.init_app(app)
    migrate.init_app(app,db)
    csrf.init_app(app)

    def setpwd(pwd):
        return "xxxx"

    # 加载到过滤器中
    app.add_template_filter(setpwd,"setP")

    # # 第一次
    # @app.before_first_request
    # def xxx():
    #     # flask 配置的加载
    #     print("before_first_request")
    # # 视图之前
    @app.before_request
    def yyy():
        from flask import request
        from FlaskPro.OA.models import Person, Permission
        userid = request.cookies.get("userid")
        # userid = int(userid)
        person = Person.query.get(userid)
        pos = Person.our_position
        print(request.path)
        # 判断该职位是否拥有权限
        if request.path == "/news.html":
            # 新闻管理
            news_perm = Permission.query.filter(Permission.per_name == "新闻管理").first()
            news_pos = news_perm.p_position  # 列表
            if pos in news_pos:
                return None
            return "你没有权限"
        # elif xxxxx == "人事管理":
        # 人事管理权限

    # 返回响应
    return app